﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication1
{
    public partial class Login : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            string name = UserName.Text;
            string pwd = Password.Text;

            string constr = "server=.;uid=sa;pwd=123456;database=Student_db";
            SqlConnection con = new SqlConnection(constr);
            
            string sql = "select * from StudentInfo where stu_name=@name and password=@pwd";
            SqlParameter[] pars =
            {
                new SqlParameter("@name",name),
                new SqlParameter("@pwd",pwd)
            };

            try
            {
                con.Open();
                SqlCommand cmd = new SqlCommand(sql,con);
                cmd.Parameters.AddRange(pars);
                
                //直接连接模式
                //int result = cmd.ExecuteNonQuery();//非查询：增、删、改，影响行数

                SqlDataReader sdr = cmd.ExecuteReader();//查询

                //cmd.ExecuteScalar();

                //断开式链接模式
                //SqlDataAdapter adapter = new SqlDataAdapter(sql,con);
                //DataSet ds = new DataSet();

                //adapter.Fill(ds);

                //if (ds.Tables[0] != null)
                //{

                //}

                if (sdr.Read())
                {
                    Session["CurrentUserName"] = name;
                    Literal1.Text = "登录成功!";
                    Response.Redirect("Home.aspx");
                }
                else
                {
                    Literal1.Text = "用户名或密码错误!";
                }


            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message.ToString());
            }
            finally
            {
                if (con != null)
                {
                    con.Close();
                }
            }


            //try
            //{
            //    using (SqlConnection con1 = new SqlConnection(constr))
            //    {



            //    }
            //}
            //catch (Exception ex)
            //{
            //    throw new Exception(ex.Message);
            //}

        }

        protected void Button2_Click(object sender, EventArgs e)
        {
            Response.Redirect("Register.aspx");
        }
    }
}